package org.groupg.practice;

import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.traverse.TopologicalOrderIterator;

public class DAG01Example {
    public static void main(String[] args) {
        // 创建一个有向图
        DefaultDirectedGraph<String, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);

        // 添加节点
        graph.addVertex("A");
        graph.addVertex("B");
        graph.addVertex("C");
        graph.addVertex("D");
        graph.addVertex("E");

        // 添加边
        graph.addEdge("A", "B");
        graph.addEdge("B", "C");
        graph.addEdge("C", "D");
        graph.addEdge("D", "E");

        // 遍历没有入边的节点（源节点）
        System.out.println("Source nodes:");
        for (String vertex : graph.vertexSet()) {
            if (graph.inDegreeOf(vertex) == 0) {
                System.out.println(vertex);
            }
        }

        // 遍历没有出边的节点（汇点）
        System.out.println("Sink nodes:");
        for (String vertex : graph.vertexSet()) {
            if (graph.outDegreeOf(vertex) == 0) {
                System.out.println(vertex);
            }
        }

        // 遍历从开始到结束的所有节点（拓扑排序）
        System.out.println("Topological sort:");
        TopologicalOrderIterator<String, DefaultEdge> toi = new TopologicalOrderIterator<>(graph);
        while (toi.hasNext()) {
            System.out.println(toi.next());
        }
    }
}
